<?php

/**
 * Created by PhpStorm.
 * Script Name: Setting.php
 * Create: 2020/5/24 上午10:25
 * Description: 站点配置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;

use app\common\model\hanzi\Config;
use app\constants\Bot;

class Hanziconfig extends Botbase
{
    /**
     * @var Config
     */
    protected $model;
    /**
     * @var array
     */
    private $tabList;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new Config();
        $this->tabList = [

        ];
    }

    /**
     * 设置
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        if(! $settings = $this->model->getOneByMap(['bot_id' => $this->bot['id'], 'key' => 'switch'], true, true)){
            $settings = $this->model->addOne([
                'key' => 'switch',
                'value' => 0,
                'admin_id' => $this->adminInfo['id'],
                'bot_id' => $this->bot['id']
            ]);
        }

        $settings['wxids'] = explode(',', $settings['wxids']);
        $members = $this->getMembers();
        $builder = new FormBuilder();
        $builder->setPostUrl(url('savePost'))
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('value', 'radio', '开启', '是否开启', [1=>'是', 0 => '否'])
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '指定对象', $members, 'required')
            ->setFormData($settings);
        return $builder->show();
    }

    public function savePost($jump_to = '/undefined', $data = [])
    {
        $jump_to = url('index');
        $post_data = input('post.');
        $post_data['admin_id'] = $this->adminInfo['id'];
        if(empty($post_data[$this->pk])){
            $this->model->addOne($post_data);
            $this->model->getOneByMap([
                'bot_id' => $this->bot['id'], 'key' => $post_data['key'], 'value' => $post_data['value']
            ], true, true);
        }else {
            $this->model->updateOne($post_data);
        }
        $this->success('数据保存成功', $jump_to);
    }
}